package ar.com.ford.it.fullEconomics.persistence.dao;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc01Coststruct;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese04Paypolicy;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp03Commodpart;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr02Requestitm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.PersistenceManager;
import com.ford.it.persistence.Query;
import com.ford.it.persistence.Transaction;

public class CommodityDao extends Dao {

    private static final String CLASS_NAME = CommodityDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);
    
    /**
     * Busca un commodity con un nombte especifico
     * 
     * @param commodity
     * Debe tener cargado el nombre del Commodity
     */
    
    public Teesp02Commodity findCommodityByName(Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "findCommodityByName";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm
                .newQuery("findCommodityByName", Teesp02Commodity.class);
        query.setParameters(commodity);
        Teesp02Commodity result = new Teesp02Commodity();

        result = (Teesp02Commodity) pm.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Da de alta el Commodity pasado por parametro
     * 
     * @param commodity
     * Debe tener cargado el nombre del Commodity
     */
    public void createCommodity(Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "createCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = null;

        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(commodity);

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Devuelve el commodity cuyo code es commodityCode listo para realizarle
     * las actualizaciones pertinentes
     * 
     * @param commodityCode
     * Code del Commodity a actualizar
     * @return
     * @throws PersistenceException
     */
    public Teesp02Commodity getCommodityForUpdate(Integer code,
                                                  Teesg01Plant plant)
            throws PersistenceException {

        String METHOD_NAME = "getCommodityForUpdate";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp02Commodity result = null;
        Teesp02Commodity pk = new Teesp02Commodity();

        pk.setEesp02CommodityNumberK(code);
        pk.setEesp02PlantCodeC(plant);
        result = (Teesp02Commodity) super.getObjForUpdate(pk);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Elimina de forma definitiva de la base de datos el commodity pasado por
     * parametro
     * 
     * @param commodity
     * Debe haber sido obtenido de la base de datos
     */
    public void deleteCommodity(Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "deleteCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(commodity);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Busca Commoditys segun code
     * 
     * @param code
     * @return
     * @throws PersistenceException
     */
    public Collection<Teesp02Commodity> findCommodities(
                                                        Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "findCommodities";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesp02Commodity> resultCol = null;
        PersistenceManager pm = null;

        pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findCommodities", Teesp02Commodity.class);
        query.setParameters(commodity);
        query.setOrdering("eesp02CommodityNameN ascending");
        resultCol = (Collection) pm.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultCol;
    }

    /**
     * Busca Commoditys segun code
     * 
     * @param code
     * @return
     * @throws PersistenceException
     */
    public Collection<Teesp02Commodity> findCommoditiesByParts(Teesp01Part part)
            throws PersistenceException {

        String METHOD_NAME = "findCommoditiesByParts";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesp03Commodpart> partCol = null;
        Collection<Teesp02Commodity> commodCol = new Vector<Teesp02Commodity>();
        PersistenceManager pm = null;
        boolean addCommodity = true;

        pm = PersistenceUtil.getPersistenceManager();
        Query partQuery = pm.newQuery("findCommodParts", Teesp03Commodpart.class);
        partQuery.setParameters(part,"normal");
        partCol = (Collection) pm.executeQuery(partQuery);
        for(Teesp03Commodpart commPart : partCol){
            addCommodity = true;
            for(Teesp02Commodity commodity : commodCol){
                if(commodity.getEesp02CommodityNumberK() == commPart.getTeesp02Commodity().getEesp02CommodityNumberK())
                    addCommodity = false;
            }
            if(addCommodity){
                commodCol.add(commPart.getTeesp02Commodity());
            }
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return commodCol;
    }

    /**
     * Busca los elementos relacionados a cierta commodity, devuelve un array de
     * 5 strings en el cual se encuentran los IDs de los elementos relacionados
     * a la commodity
     * 
     * @param code
     * @return String[] 5 strings con la concatenacion de los IDs de las 5
     * tablas relacionadas a commosity.
     * @throws PersistenceException
     */
    public String[] commodityRelatedElements(Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "commodityReletadeElements";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesc01Coststruct> commCostStructures = null;
        Iterator<Teesc01Coststruct> costStrucIt = null;

        Collection<Teese04Paypolicy> commPayPolicies = null;
        Iterator<Teese04Paypolicy> payPolicyIt = null;

        Collection<Teesr02Requestitm> commRequestItems = null;
        Iterator<Teesr02Requestitm> reqItemIt = null;

        Collection<Teesp03Commodpart> commParts = null;
        Iterator<Teesp03Commodpart> commPartsIt = null;

        Collection<Teesr04Agreemitem> commAgreemItems = null;
        Iterator<Teesr04Agreemitem> agreemItemIt = null;

        String[] commRelatedElementsIDs = new String[5];
        PersistenceManager pm = null;

        pm = PersistenceUtil.getPersistenceManager();
        Query costStrucureQuery = pm.newQuery("findCommoditysCostStructures",
                Teesc01Coststruct.class);
        costStrucureQuery.setParameters(commodity, "eesc01PlantCodeC");
        commCostStructures = (Collection) pm.executeQuery(costStrucureQuery);
        if (commCostStructures.isEmpty()) {
            commRelatedElementsIDs[0] = null;
        } else {
            costStrucIt = commCostStructures.iterator();
            commRelatedElementsIDs[0] = costStrucIt.next()
                    .getEesc01CststrNumberK().toString();
            while (costStrucIt.hasNext()) {
                commRelatedElementsIDs[0] += ", "
                        + costStrucIt.next().getEesc01CststrNumberK()
                                .toString();
            }
        }

       /* Query paymentPolicyQuery = pm.newQuery("findCommoditysPaymentPolicies",
                Teese04Paypolicy.class);
        paymentPolicyQuery.setParameters(commodity, "eese04PlantCodeC");
        commPayPolicies = (Collection) pm.executeQuery(paymentPolicyQuery);
        if (commPayPolicies.isEmpty()) {
            commRelatedElementsIDs[1] = null;
        } else {
            payPolicyIt = commPayPolicies.iterator();
            commRelatedElementsIDs[1] = payPolicyIt.next()
                    .getEese04PaypolNumberK().toString();
            while (payPolicyIt.hasNext()) {
                commRelatedElementsIDs[1] += ", "
                        + payPolicyIt.next().getEese04PaypolNumberK()
                                .toString();
            }
        }*/

        Query requesQuery = pm.newQuery("findCommoditysRequests",
                Teesr02Requestitm.class);
        requesQuery.setParameters(commodity, "eesr02PlantCodeC");
        commRequestItems = (Collection) pm.executeQuery(requesQuery);
        if (commRequestItems.isEmpty()) {
            commRelatedElementsIDs[2] = null;
        } else {
            reqItemIt = commRequestItems.iterator();
            commRelatedElementsIDs[2] = reqItemIt.next()
                    .getEesr02ReqitmNumberK().toString();
            while (reqItemIt.hasNext()) {
                commRelatedElementsIDs[2] += ", "
                        + reqItemIt.next().getEesr02ReqitmNumberK().toString();
            }
        }

        Query commonPartQuery = pm.newQuery("findCommoditysParts",
                Teesp03Commodpart.class);
        commonPartQuery.setParameters(commodity);
        commParts = (Collection) pm.executeQuery(commonPartQuery);
        if (commParts.isEmpty()) {
            commRelatedElementsIDs[3] = null;
        } else {
            commPartsIt = commParts.iterator();
            Teesp03Commodpart commPart = commPartsIt.next();
            commRelatedElementsIDs[3] = commPart.getTeesp01Part()
                    .getEesp01PartPrefixCodeC()
                    + "_"
                    + commPart.getTeesp01Part().getEesp01PartBaseCodeC()
                    + "_"
                    + commPart.getTeesp01Part().getEesp01PartSuffixCodeC();
            while (commPartsIt.hasNext()) {
                commPart = commPartsIt.next();
                commRelatedElementsIDs[3] += ", "
                        + commPart.getTeesp01Part().getEesp01PartPrefixCodeC()
                        + "_"
                        + commPart.getTeesp01Part().getEesp01PartBaseCodeC()
                        + "_"
                        + commPart.getTeesp01Part().getEesp01PartSuffixCodeC();
            }
        }

        Query agreementQuery = pm.newQuery("findCommoditysAgreements",
                Teesr04Agreemitem.class);
        agreementQuery.setParameters(commodity, "eesr04PlantCodeC");
        commAgreemItems = (Collection) pm.executeQuery(agreementQuery);
        if (commAgreemItems.isEmpty()) {
            commRelatedElementsIDs[4] = null;
        } else {
            agreemItemIt = commAgreemItems.iterator();
            commRelatedElementsIDs[4] = agreemItemIt.next()
                    .getEesr04AgritmNumberK().toString();
            while (agreemItemIt.hasNext()) {
                commRelatedElementsIDs[4] += ", "
                        + agreemItemIt.next().getEesr04AgritmNumberK()
                                .toString();
            }
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return commRelatedElementsIDs;
    }
}
